package teamblue.cardex.activities;

import java.io.IOException;
import java.text.DateFormat;
import java.util.List;

import teamblue.cardex.R;
import teamblue.cardex.components.Card;
import teamblue.cardex.components.CardexDb;
import android.app.Activity; 
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
//import android.content.res.Configuration;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
//import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class CardView extends Activity{
	
	private CardexDb mDb;
	private ImageView icon;
	private TextView name;
	private TextView note;
	private TextView num;
	private TextView balance;
	private TextView pin;
	private TextView phone;
	private TextView url;
	private TextView expire;
	private Card mCard;
	private int button_checked;
	
	private final static int UPDATE_CARD=0;
	private final static int DELETE_CARD=1;
	private final static int RETURN=2;
	private final static int DELETE_DIALOG = 3;
	private final static int UNABLE_TO_FIND_DIALOG = 4;
	private final static int BARCODE_DIALOG = 5;
	private final static int BARCODE = 6;
	private final static int BALANCE_CHANGE = 7;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		mDb = new CardexDb(this).open();
		this.setContentView(R.layout.single_card_view);
		icon = (ImageView)findViewById(R.id.single_card_view_item_card_icon);
		name = (TextView)findViewById(R.id.single_card_view_item_card_name);
		note = (TextView)findViewById(R.id.single_card_view_item_note_value);
		num = (TextView)findViewById(R.id.single_card_view_item_card_num_value);
		balance = (TextView)findViewById(R.id.single_card_view_item_balance_value);
		pin = (TextView)findViewById(R.id.single_card_view_item_card_pin_value);
		phone = (TextView)findViewById(R.id.single_card_view_item_card_phone);
		url = (TextView)findViewById(R.id.single_card_view_item_card_url);
		expire = (TextView)findViewById(R.id.single_card_view_item_exp_date_value);
		Button mapbutton = (Button)findViewById(R.id.single_card_view_item_map_it);
		Button barcodebutton = (Button)findViewById(R.id.single_card_view_item_barcode);	
		
		updateDisplay();
		
	  mapbutton.setOnClickListener(new View.OnClickListener() {
		  public void onClick(View view) {
			  Geocoder geocoder = new Geocoder(CardView.this);
			  LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
			  Criteria criteria = new Criteria();
			  criteria.setAccuracy(Criteria.ACCURACY_FINE);
			  criteria.setAltitudeRequired(false);
			  criteria.setBearingRequired(false);
			  criteria.setSpeedRequired(false);
			  criteria.setCostAllowed(true);
			  criteria.setPowerRequirement(Criteria.POWER_LOW);
			  String provider = locationManager.getBestProvider(criteria, true);
			  if(provider == null){
				  showDialog(UNABLE_TO_FIND_DIALOG);
				  return;
			  }
			  Location currentLocation = locationManager.getLastKnownLocation(provider);
			  if(currentLocation == null){
				  showDialog(UNABLE_TO_FIND_DIALOG);
				  return;
			  }
			  try {
				List<Address> result = geocoder.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
				String city = result.get(0).getLocality();
				if(city == null) city = "";
				city = city.replace(" ", "+");
				String state = result.get(0).getAdminArea();
				if(state == null) state = "";
				state = state.replace(" ", "+");
				String query = new String(mCard.name);
				query = query.replace(" ", "+");
				query = query.replace("&", "and");
				String uri = "geo:0,0?q="+query+"+"+city+"+"+state;
				Log.d("URI",uri);
				startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri)));
			} catch (IOException e) {
				showDialog(UNABLE_TO_FIND_DIALOG);
				e.printStackTrace();
			}
				  
	      } 
	  });
	  barcodebutton.setOnClickListener(new View.OnClickListener(){
		  public void onClick(View view) {
			  if(mCard.format == null)
				  showDialog(BARCODE_DIALOG);
			  else{
				  BarcodeDialog bc = new BarcodeDialog(CardView.this,BarcodeFormat.valueOf(mCard.format),
						  mCard.barcode,getWindowManager().getDefaultDisplay().getWidth(),
						  getWindowManager().getDefaultDisplay().getHeight());
				  bc.show();
			  }
		  }
	  });
	  balance.setOnClickListener(new View.OnClickListener(){
		  public void onClick(View view) {
				  showDialog(BALANCE_CHANGE);
			  }
	  });
	}

	@Override
	public void onResume(){
		super.onResume();
		updateDisplay();
	}
	
	protected void onActivityResult (int requestCode, int resultCode, Intent data) {
		switch(requestCode) {
		case IntentIntegrator.REQUEST_CODE:
			if(resultCode == RESULT_OK){
				IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
				if (scanResult != null) {
					mCard.barcode=scanResult.getContents();
					mCard.format=scanResult.getFormatName();
					mDb.updateCard(mCard);
				}
			}
		}
	}
	 
	//MAIN MENU BUTTON POPUP
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			menu.add(0, UPDATE_CARD, 0, R.string.update_card).setIcon(android.R.drawable.ic_menu_edit);
			menu.add(0, BARCODE, 0, R.string.barcode_button).setIcon(android.R.drawable.ic_menu_camera);
			menu.add(0, DELETE_CARD, 0, R.string.delete_card).setIcon(android.R.drawable.ic_menu_delete);
		    menu.add(0, RETURN, 0, R.string.go_back).setIcon(android.R.drawable.ic_menu_revert);
		    return true;
		}
		// HANDLES MENU ITEM SELECTIONS
		
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			Card mCard = mDb.getCard(getIntent().getLongExtra(CardexDb.CARD_ID, -1));
		    switch (item.getItemId()) {
		    case UPDATE_CARD:
		    	Intent changeCard = new Intent(getApplicationContext(), AddEditCard.class);
				changeCard.putExtra(CardexDb.CARD_ID, mCard.id);
				startActivity(changeCard);
		        return true;
		    case DELETE_CARD:
		    	showDialog(DELETE_DIALOG);
		    	return true;
		    case BARCODE:
		    	showDialog(BARCODE_DIALOG);
		    	return true;
		    case RETURN:
		    	this.finish();
		        return true;
		    }
		    return false;
		}
		
		private void updateDisplay(){
			
			mCard = mDb.getCard(getIntent().getLongExtra(CardexDb.CARD_ID, -1));
			 
			Card.setIcon(mCard.icon, icon, mCard.name, mCard.editable);
			name.setText(mCard.name);
			if(mCard.note != null){
				note.setVisibility(View.VISIBLE);
				note.setText(mCard.note);
			}
			else note.setVisibility(View.GONE);
			if(mCard.barcode != null){
				num.setVisibility(View.VISIBLE);
				int length = mCard.barcode.length();
				if(length > 4){
					String card_number= new String(mCard.barcode.substring(0, 4));
					for(int i = 4; i < length; i++){
						Log.e("count", ""+i+" " +mCard.barcode.substring(i, i+1));
						if(i%4 == 0) card_number = card_number.concat(" ");
						card_number = card_number.concat(mCard.barcode.substring(i, i+1));
					}
					num.setText(card_number);
				}
				else num.setText(mCard.barcode);
			}
			else num.setVisibility(View.GONE);
			if(mCard.balance != -1){
				balance.setVisibility(View.VISIBLE);
				balance.setText("$" + AddEditCard.my_format.format(mCard.balance));
			}
			else balance.setVisibility(View.GONE);
			if(mCard.pin != null){
				findViewById(R.id.single_card_view_item_card_pin_row).setVisibility(View.VISIBLE);
				pin.setText(mCard.pin);
			}
			else findViewById(R.id.single_card_view_item_card_pin_row).setVisibility(View.GONE);
			if(mCard.phone != null){
				findViewById(R.id.single_card_view_item_card_phone_row).setVisibility(View.VISIBLE);
				phone.setText(mCard.phone);
			}
			else findViewById(R.id.single_card_view_item_card_phone_row).setVisibility(View.GONE);
			if(mCard.url != null){
				url.setVisibility(View.VISIBLE);
				url.setText(mCard.url);
			}
			else url.setVisibility(View.GONE);
			if(mCard.expire != null){
				expire.setVisibility(View.VISIBLE);
				expire.setText(getResources().getString(R.string.expires)+" "+DateFormat.getDateInstance().format(mCard.expire));
			}
			else expire.setVisibility(View.GONE);
		}
		
		@Override
		public void onDestroy(){
			super.onDestroy();
			mDb.close();
		}
		@Override
		public Dialog onCreateDialog(int id) {
			switch(id){
			case DELETE_DIALOG:
		    	return new AlertDialog.Builder(this)
		    	.setMessage(getResources().getString(R.string.delete_dialog)+" "+mCard.name+"?")
		    		.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialog, int which) {
							mDb.removeCard(mCard.id);
							finish();
						}
		    		})
		    		.setNegativeButton(R.string.no, new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
		    		}).create();
			case UNABLE_TO_FIND_DIALOG:
				return new AlertDialog.Builder(this)
		    	.setMessage(R.string.unable_to_find_dialog)
		    		.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
		    		}).create();
			case BARCODE_DIALOG:
				return new AlertDialog.Builder(this).setMessage(R.string.no_barcode_dialog)
				.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int which) {
						IntentIntegrator.initiateScan(CardView.this);
					}
				})
				.setNegativeButton(R.string.no, new DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).create();
			case BALANCE_CHANGE:
				AlertDialog.Builder builder;
				AlertDialog alertDialog;

				LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
				View layout = inflater.inflate(R.layout.balance_dialog, (ViewGroup)findViewById(R.id.layout_root));
				
				builder = new AlertDialog.Builder(this);
				builder.setView(layout);
				alertDialog = builder.create();
				alertDialog.setTitle("Update Balance");
				
				RadioGroup rgroup = (RadioGroup) layout.findViewById(R.id.group1);
				//RadioButton subtract = (RadioButton) layout.findViewById(R.id.option1);				
				//RadioButton change = (RadioButton) layout.findViewById(R.id.option2);				
				Button enter_button = (Button) layout.findViewById(R.id.balance_change_button);
				final EditText balchange = (EditText)layout.findViewById(R.id.balance_change_balance_entry);
				rgroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						if(checkedId==R.id.option1)
						{
							button_checked = 0;
						}
						else if(checkedId==R.id.option2)
						{
							button_checked = 1;
						}
						else
						{
							button_checked = 2;
						}
		            }
				 });
				
				enter_button.setOnClickListener(new View.OnClickListener(){
					  public void onClick(View view) {
						  String field = null;
						  mCard = mDb.getCard(getIntent().getLongExtra(CardexDb.CARD_ID, -1));
						  if(button_checked==0)
						  {
							  	field = balchange.getText().toString();
								if(!field.equals("")) 
								{
									mCard.balance = mCard.balance - Double.parseDouble(field);
									if(mCard.balance<0.00)
									{
										mCard.balance=0;
									}
								}
								else mCard.balance = mCard.balance;
								mDb.updateCard(mCard);
								balance.setText("$" + AddEditCard.my_format.format(mCard.balance));
						  }
						  else if(button_checked==1)
						  {
							  field = balchange.getText().toString();
								if(!field.equals("")) 
								{
									mCard.balance = Double.parseDouble(field);
									if(mCard.balance<0.00)
									{
										mCard.balance=0;
									}
								}
								else mCard.balance = mCard.balance;
								mDb.updateCard(mCard);
								balance.setText("$" + AddEditCard.my_format.format(mCard.balance));
						  }
						  
						  dismissDialog(BALANCE_CHANGE);
					  }
				 });
				return alertDialog;
				
			default:
				return null;
				
			}
		}

}
